<template>
  <div class="image-picker-container">
    <el-tabs v-model="activeImages" v-if="isDataReady" >
      <el-tab-pane
        v-for="tab in tabs"
        :key="tab.name"
        :label="tab.label"
        :name="tab.name"
      >
        <div class="icon-picker-box" v-if=" tab.images.length>0">
        <LazyImage
          :index="idx" v-for="(image, idx) in tab.images" :key="idx" :src="image.url"
          :id="image._id"
          :class="{'image-picker-item-active': value === image.path}"
          class="image-picker-item" draggable="false"
          @click.native="select(image.path)">
          <!-- 图片加载之前默认在图片元素上方展示的样式--自由发挥 -->
          <div class="slot-txt" v-loading="loading"></div>
          <template #err>
            <!-- 图片加载失败后在上面展示的样式--- 自由发挥 -->
            <div class="slot-txt">加载失败</div>
          </template>
        </LazyImage>
        </div>
        <div v-else class="pad-all">
          <EmptyContent :min-height="150" :image-size="120" empty-text="暂无可用图片"></EmptyContent>
        </div>
      </el-tab-pane>
    </el-tabs>

  </div>

</template>

<script>
  import {assetBaseUrl} from '@/config/env';
  import EmptyContent from "@/components/IDE/EmptyContent.vue";
  import LazyImage from "@/components/IDE/LazyImage.vue";
  import {mapState} from "vuex";
  import iconfont from "@/assets/font/iconfont.json";
  import {imageCategory} from "@/config/common";
  export default {
    name: 'ImagePicker',
    components: {
      EmptyContent, LazyImage
    },
    model: {
      event: 'change'
    },
    props: {
      value: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        loading: true,
        activeImages: 'first',
        // tabs: [],
        isDataReady: false,
        imageCategory:imageCategory
      };
    },
    computed: {
	    ...mapState({
		    imageAssetsList: state => state.ide.imageAssetsList,
	    }),
      images() {
        return this.imageAssetsList.map(image => {
					const {_id, name, path,assetType,imageType} = image;
          return {
	          _id: _id,
	          name: name,
            assetType: assetType,
            imageType: imageType,
	          path: path,
            url: `${assetBaseUrl}/file/download/${path}`
          };
        });
      },
      tabs(){
        //实时计算tabs
        const commonAssets = this.images.filter(asset => asset.assetType === 'common');
        const projectAssets = this.images.filter(asset => !asset.assetType || asset.path.includes('asset/project'));
        const categorizedCommonAssets = imageCategory.reduce((acc, category) => {
          acc[category.value] = commonAssets.filter(asset => asset.imageType === category.value);
          return acc;
        }, {});
        categorizedCommonAssets.other.push(...commonAssets.filter(asset => !asset.imageType));
        return [
          { label: '图标', name: 'first', images:categorizedCommonAssets.icons},
          { label: 'logo', name: 'second', images:categorizedCommonAssets.logo},
          { label: '背景', name: 'third', images:categorizedCommonAssets.bg},
          { label: 'gif', name: 'fourth', images:categorizedCommonAssets.gifs},
          { label: '其他', name: 'fifty', images:categorizedCommonAssets.other},
          { label: '项目', name: 'sixty', images:projectAssets},
        ];
      }
    },
    watch: {
      value(newValue) {
        this.updateActiveTab(newValue);
      }
    },
    mounted() {
      this.loadTabs();
      this.$EventBus.$on('jumpToImage', (image) => {
        if (image) {
          let timer = setTimeout(() => {
            const element = document.getElementById(image);
            if (!element) return;
            element.scrollIntoView({block: 'center', behavior: 'smooth'});
            clearTimeout(timer);
            timer = null;
          }, 300);
        }
      });
    },
    beforeDestroy() {
      this.$EventBus.$off('jumpToImage');
    },
    methods: {
      loadTabs() {
        this.isDataReady = true;
         this.updateActiveTab(this.value); // 初始化时根据 value 设置 activeIcons
      },
      updateActiveTab(path) {
        for (const tab of this.tabs) {
          if (tab.images.some(icon => icon.path === path)) {
            this.activeImages = tab.name || 'first';
            break;
          }
        }
      },
      select(path) {
        this.$emit('change', this.value === path ? '' : path);
      }
    }
  };
</script>

<style scoped lang="less">
  .image-picker-container {
    min-height: 350px;
    .icon-picker-box{
      display: flex;
      justify-content: flex-start;
      gap: 5px;
      flex-wrap: wrap;
      max-height: 350px;
      min-height: 200px;
      overflow: auto;
      text-align: justify;
    }
    .image-picker-item {
      width: 60px;
      height: 60px;
      background: @colorGray95;
      object-fit: contain;
      cursor: pointer;
      padding: 5px;
      margin: 5px;
      border: 1px @colorGray90 solid;
    }

    .image-picker-item-active {
      border: 1px @colorPrimary solid;
    }
  }
</style>
